{% extends "layui/admin/base.html" %}
{% block title %}网站管理{% endblock %}

{% block content %}
    <blockquote class="layui-elem-quote">
        <p><a href="/admin/v2"><i class="layui-icon layui-icon-home"></i> 首页</a>
            <i class="layui-icon layui-icon-next"></i> 网站管理</p>
    </blockquote>
    <div class="layui-panel">
        <br>
        <div class="layui-card">
            <div class="layui-card-header">
                <h1>网站列表</h1>
            </div>
            <div class="layui-card-body">
                <table id="websiteTable" lay-filter="websiteTableFilter"></table>
            </div>
        </div>
        <!-- 表格工具栏 -->
        <script type="text/html" id="toolbar">
            <div class="layui-btn-container">
                 <button class="layui-btn" id="addBtn">添加网站</button>
                <button class="layui-btn layui-btn-sm layui-bg-blue" id="reload">
                    刷新
                    <i class="layui-icon layui-icon-down layui-font-12"></i>
                </button>
            </div>
        </script>
        <!-- 弹窗表单 -->
        <div id="websiteFormModal" style="display:none; padding:20px;">
            <form class="layui-form" lay-filter="websiteForm" enctype="multipart/form-data">
                <input type="hidden" name="id">

                <div class="layui-form-item">
                    <label class="layui-form-label">名称</label>
                    <div class="layui-input-block">
                        <input type="text" name="name" required lay-verify="required" placeholder="请输入名称"
                               class="layui-input">
                    </div>
                </div>

                <div class="layui-form-item">
                    <label class="layui-form-label">网址</label>
                    <div class="layui-input-block">
                        <input type="text" name="url" required lay-verify="required|url" placeholder="请输入网址"
                               class="layui-input">
                    </div>
                </div>

                <div class="layui-form-item">
                    <label class="layui-form-label">描述</label>
                    <div class="layui-input-block">
                        <input type="text" name="description" placeholder="可选" class="layui-input">
                    </div>
                </div>

                <!-- logo选择 -->
                <div class="layui-form-item">
                    <label class="layui-form-label">Logo 类型</label>
                    <div class="layui-input-block">
                        <input type="radio" name="logo_type" value="url" title="外链" checked>
                        <input type="radio" name="logo_type" value="upload" title="上传">
                    </div>
                </div>

                <!-- 外链logo输入 -->
                <div class="layui-form-item" id="logoUrlGroup">
                    <label class="layui-form-label">Logo URL</label>
                    <div class="layui-input-block">
                        <input type="text" name="logo_url" placeholder="填写外链图片地址" class="layui-input">
                    </div>
                </div>

                <!-- 上传logo文件 -->
                <div class="layui-form-item" id="logoUploadGroup" style="display:none;">
                    <label class="layui-form-label">上传 Logo</label>
                    <div class="layui-input-block">
                        <input type="file" name="logo_file" accept="image/*" class="layui-upload-file">
                    </div>
                </div>

                <!-- logo 预览 -->
                <div class="layui-form-item">
                    <label class="layui-form-label">Logo 预览</label>
                    <div class="layui-input-block">
                        <img id="logoPreview" src="" alt="Logo预览"
                             style="max-height:60px; max-width:160px; border:1px solid #ccc; display:none;">
                    </div>
                </div>

                <!-- 分类下拉 -->
                <div class="layui-form-item">
                    <label class="layui-form-label">分类</label>
                    <div class="layui-input-block">
                        <select name="category_id" lay-verify="required">
                            <option value="">请选择分类</option>
                        </select>
                    </div>
                </div>

                <div class="layui-form-item">
                    <div class="layui-input-block">
                        <button class="layui-btn" lay-submit lay-filter="submitWebsite">提交</button>
                    </div>
                </div>
            </form>
        </div>
    </div>
{% endblock %}

{% block scripts %}
    <script>
        layui.use(['table', 'form', 'layer'], function () {
            const table = layui.table;
            const form = layui.form;
            const layer = layui.layer;
            const $ = layui.$;

            let uploadLogoFile = null;  // 用来存储上传的文件对象

            // 加载分类选项
            function loadCategories(selectedId = '') {
                $.ajax({
                    url: '/api/categories/',
                    type: 'GET',
                    headers: {Authorization: 'Bearer ' + localStorage.getItem('token')},
                    success: function (res) {
                        const select = $('select[name="category_id"]');
                        select.empty();
                        select.append('<option value="">请选择分类</option>');
                        res.data.forEach(cat => {
                            const selected = selectedId === String(cat.id) ? 'selected' : '';
                            select.append(`<option value="${cat.id}" ${selected}>${cat.name}</option>`);
                        });
                        form.render('select');
                    }
                });
            }

            // 表格渲染
            table.render({
                elem: '#websiteTable',
                url: '/api/websites/',
                method: 'get',
                headers: {'Authorization': 'Bearer ' + localStorage.getItem('token')},
                page: true,
                toolbar: "#toolbar",
                defaultToolbar: ['filter', 'print', 'exports'],
                parseData: res => ({
                    code: res.code,
                    msg: res.msg,
                    count: res.count,
                    data: res.data
                }),
                cols: [[
                    {field: 'id', title: 'ID', width: 60},
                    {
                        field: 'local_logo',
                        title: 'Logo',
                        width: 80,
                        templet: d => {
                            const src = d.local_logo || d.logo || '';
                            return src ? `<a href="${src}" target="_blank"><img src="${src}" alt="${d.name}" style="max-width:30px;"></a>` : '';
                        }
                    },
                    {field: 'name', title: '名称', width: 120},
                    {field: 'url', title: '网址', templet: d => `<a href="${d.url}" target="_blank">${d.url}</a>`},
                    {field: 'description', title: '描述'},
                    {
                        title: '分类',
                        width: 100,
                        templet: d => d.category ? d.category.name : ''
                    },
                    {
                        title: '操作', width: 160, templet: d => `
                          <button class="layui-btn layui-btn-xs" lay-event="edit">编辑</button>
                          <button class="layui-btn layui-btn-danger layui-btn-xs" lay-event="delete">删除</button>`
                    }
                ]],
                text: {none: '暂无数据'}
            });

            // 切换logo类型
            form.on('radio(logo_type)', function (data) {
                if (data.value === 'url') {
                    $('#logoUrlGroup').show();
                    $('#logoUploadGroup').hide();
                    uploadLogoFile = null;
                    $('input[name="logo_file"]').val('');
                    $('input[name="logo_url"]').trigger('input'); // 触发外链预览更新
                } else {
                    $('#logoUrlGroup').hide();
                    $('#logoUploadGroup').show();
                    $('input[name="logo_url"]').val('');
                    $('#logoPreview').hide().attr('src', '');
                }
            });

            // 外链 logo 预览
            $('input[name="logo_url"]').on('input', function () {
                const url = $(this).val().trim();
                if (url) {
                    $('#logoPreview').attr('src', url).show();
                } else {
                    $('#logoPreview').hide().attr('src', '');
                }
            });

            // 选择上传文件，实时预览但不上传
            $('input[name="logo_file"]').on('change', function () {
                const file = this.files[0];
                if (!file) return;
                if (!file.type.startsWith('image/')) {
                    layer.msg('请选择图片文件');
                    $(this).val('');
                    return;
                }
                uploadLogoFile = file;

                const reader = new FileReader();
                reader.onload = e => {
                    $('#logoPreview').attr('src', e.target.result).show();
                };
                reader.readAsDataURL(file);
            });

            // 添加按钮
            $('#addBtn').on('click', function () {
                $('form')[0].reset();
                $('input[name="id"]').val('');
                uploadLogoFile = null;
                $('#logoPreview').hide().attr('src', '');
                form.render();
                loadCategories();
                layer.open({
                    type: 1,
                    title: '添加网站',
                    content: $('#websiteFormModal'),
                    area: ['520px']
                });
            });

            // 编辑按钮
            table.on('tool(websiteTableFilter)', function (obj) {
                const data = obj.data;
                if (obj.event === 'edit') {
                    uploadLogoFile = null;
                    loadCategories(String(data.category_id));
                    form.val('websiteForm', {
                        id: data.id,
                        name: data.name,
                        url: data.url,
                        description: data.description,
                        category_id: data.category_id,
                    });

                    // 根据是否有上传的本地 logo 判断 logo 类型及预览
                    if (data.local_logo) {
                        // 默认选择外链，因为你接口里存储的本地 logo 是URL地址
                        form.val('websiteForm', {logo_type: 'url', logo_url: data.local_logo});
                        $('#logoUrlGroup').show();
                        $('#logoUploadGroup').hide();
                        $('#logoPreview').attr('src', data.local_logo).show();
                    } else if (data.logo) {
                        form.val('websiteForm', {logo_type: 'url', logo_url: data.logo});
                        $('#logoUrlGroup').show();
                        $('#logoUploadGroup').hide();
                        $('#logoPreview').attr('src', data.logo).show();
                    } else {
                        form.val('websiteForm', {logo_type: 'url', logo_url: ''});
                        $('#logoPreview').hide().attr('src', '');
                    }

                    form.render();
                    layer.open({
                        type: 1,
                        title: '编辑网站',
                        content: $('#websiteFormModal'),
                        area: ['520px']
                    });
                } else if (obj.event === 'delete') {
                    layer.confirm('确定删除该网站？', function (index) {
                        $.ajax({
                            url: `/api/website/${data.id}`,
                            type: 'DELETE',
                            headers: {Authorization: 'Bearer ' + localStorage.getItem('token')},
                            success: res => {
                                layer.msg('删除成功');
                                table.reload('websiteTable', {page: {curr: 1}});
                            },
                            error: () => layer.msg('删除失败')
                        });
                        layer.close(index);
                    });
                }
            });

            // 提交表单（上传logo文件时先上传图片）
            form.on('submit(submitWebsite)', function (data) {
                const formData = new FormData();
                const vals = data.field;

                // 必填校验（layui会自动提示，但这里加强）
                if (!vals.name || !vals.url || !vals.category_id) {
                    layer.msg('名称、网址和分类为必填项');
                    return false;
                }

                // 先处理logo上传或使用外链
                if (vals.logo_type === 'upload' && uploadLogoFile) {
                    // 上传图片接口示例，需你实现
                    let uploadUrl = '/api/upload/logo';

                    let imageFormData = new FormData();
                    imageFormData.append('file', uploadLogoFile);

                    layer.load();
                    $.ajax({
                        url: uploadUrl,
                        type: 'POST',
                        data: imageFormData,
                        contentType: false,
                        processData: false,
                        headers: {Authorization: 'Bearer ' + localStorage.getItem('token')},
                        success: res => {
                            layer.closeAll('loading');
                            if (res.code === 0 && res.data && res.data.url) {
                                submitWebsiteData(res.data.url);
                            } else {
                                layer.msg('上传logo失败');
                            }
                        },
                        error: () => {
                            layer.closeAll('loading');
                            layer.msg('上传logo接口错误');
                        }
                    });
                } else if (vals.logo_type === 'url') {
                    submitWebsiteData(vals.logo_url || '');
                } else {
                    // 没有logo，直接提交
                    submitWebsiteData('');
                }

                // 统一提交网站信息函数
                function submitWebsiteData(logoUrl) {
                    formData.append('name', vals.name);
                    formData.append('url', vals.url);
                    formData.append('description', vals.description || '');
                    formData.append('logo', logoUrl);
                    formData.append('category_id', vals.category_id);

                    const websiteId = vals.id;
                    let ajaxOptions = {
                        url: websiteId ? `/api/website/${websiteId}` : '/api/websites/add',
                        type: websiteId ? 'PUT' : 'POST',
                        data: formData,
                        contentType: false,
                        processData: false,
                        headers: {Authorization: 'Bearer ' + localStorage.getItem('token')},
                        success: res => {
                            layer.msg(res.msg || '操作成功');
                            layer.closeAll();
                            table.reload('websiteTable', {page: {curr: 1}});
                            uploadLogoFile = null;
                        },
                        error: xhr => {
                            layer.msg(xhr.responseJSON?.msg || '操作失败');
                        }
                    };

                    // PUT 需要传 json，POST 传 form-data，你的接口好像POST用form-data，PUT用json，调整一下这里
                    if (websiteId) {
                        // PUT 用 JSON
                        ajaxOptions.contentType = 'application/json';
                        ajaxOptions.processData = true;
                        let obj = {};
                        formData.forEach((v, k) => {
                            obj[k] = v;
                        });
                        ajaxOptions.data = JSON.stringify(obj);
                    }

                    $.ajax(ajaxOptions);
                }

                return false; // 阻止表单自动提交
            });
        });
    </script>
{% endblock %}
